<template>
  <div class="task-management">
    <!-- 上部分：筛选条件 -->
    <div class="filter-bar">
      <div class="filter-controls">
        <el-input
            v-model="filterTaskName"
            placeholder="任务类型名称"
            clearable
            style="width: 200px"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select
            v-model="filterStatus"
            placeholder="任务类型状态"
            clearable
            style="width: 120px"
        >
          <el-option label="全部状态" value="" />
          <el-option label="正常" value="1" />
          <el-option label="停用" value="0" />
        </el-select>
        <el-button type="primary" @click="searchTasks">
          查询
        </el-button>
        <el-button @click="resetFilter">
          重置
        </el-button>
      </div>
    </div>

    <!-- 下部分：任务类型表格 -->
    <div class="table-section">
      <div class="table-header">
        <h3>任务类型列表</h3>
        <div class="table-controls">
          <el-button size="small" type="success" @click="addNewTask">
            添加任务类型
          </el-button>
        </div>
      </div>
      <div class="table-container">
        <el-table
            :data="taskTreeData"
            style="width: 100%; height: 100%;"
            row-key="id"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            stripe
            :header-cell-style="{ background: '#f8f9fa', color: '#333', fontWeight: '500', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
            border
            v-loading="loading"
        >
          <el-table-column prop="typeName" label="任务类型名称" min-width="200" align="left">
            <template #default="scope">
              <span>{{ scope.row.typeName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" min-width="160" align="center">
            <template #default="scope">
              <div class="time-cell">
                <el-icon><Clock /></el-icon>
                <span>{{ formatTaskTime(scope.row.createTime) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getTaskStatusType(scope.row.status)" size="small">
                {{ getTaskStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" align="center" fixed="right">
            <template #default="scope">
              <div class="action-buttons">
                <el-button size="small" type="primary" @click="addChildTask(scope.row)">
                  添加子级
                </el-button>
                <el-button size="small" type="warning" @click="editTask(scope.row)">
                  编辑
                </el-button>
                <el-button size="small" type="danger" @click="deleteTask(scope.row)">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加/编辑任务类型弹窗 -->
    <el-dialog
        v-model="showAddDialog"
        :title="isEdit ? '编辑任务类型' : isChild ? '添加子任务类型' : '添加任务类型'"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form :model="taskForm" label-width="120px" :rules="taskRules" ref="taskFormRef">
        <el-form-item label="任务类型名称" prop="typeName">
          <el-input
              v-model="taskForm.typeName"
              placeholder="请输入任务类型名称"
              maxlength="50"
              show-word-limit
          />
        </el-form-item>
        <el-form-item label="父级任务类型" prop="pid" v-if="!isChild">
          <el-select
              v-model="taskForm.pid"
              placeholder="请选择父级任务类型"
              style="width: 100%"
              clearable
              filterable
          >
            <el-option label="无父级" :value="0" />
            <el-option
                v-for="item in parentTaskOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务类型状态" prop="status">
          <el-select v-model="taskForm.status" placeholder="请选择任务类型状态" style="width: 100%">
            <el-option label="正常" value="1" />
            <el-option label="停用" value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelEdit">取消</el-button>
        <el-button
            type="primary"
            @click="saveTask"
            :loading="saveLoading"
        >
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { Clock, Search, Edit, Delete, Plus, DataLine, VideoPlay, Timer, Folder } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { taskTypeAPI } from '../api/index.js'

const router = useRouter()

// 响应式数据
const filterTaskName = ref('')
const filterStatus = ref('')
const showAddDialog = ref(false)
const isEdit = ref(false)
const isChild = ref(false)
const taskFormRef = ref()
const loading = ref(false)
const saveLoading = ref(false)

// 任务类型列表数据
const taskTreeData = ref([])
const parentTaskOptions = ref([])

// 任务类型表单数据
const taskForm = ref({
  id: '',
  typeName: '',
  pid: 0,
  status: '1', // 默认状态：1=正常
})

// 表单验证规则
const taskRules = {
  typeName: [
    { required: true, message: '请输入任务类型名称', trigger: 'blur' },
    { min: 2, max: 50, message: '任务类型名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  status: [{ required: true, message: '请选择任务类型状态', trigger: 'change' }]
}

// 加载任务类型列表
const loadTaskList = async () => {
  loading.value = true;
  try {
    const params = {
      typeName: filterTaskName.value || '',
      status: filterStatus.value || ''
    };

    console.log('请求任务类型列表参数:', params);

    const result = await taskTypeAPI.getTaskTypeList(params);

    if (result && result.code === 0) {
      console.log(result);
      taskTreeData.value = result.data || [];
      console.log('任务类型列表加载成功:', taskTreeData.value.length, '个任务类型');

      // 加载父级任务选项
      loadParentTaskOptions();
    } else {
      throw new Error(result?.msg || '获取任务类型列表失败');
    }
  } catch (error) {
    console.error('加载任务类型列表失败:', error);
    ElMessage.error(`加载任务类型列表失败: ${error.message}`);
    taskTreeData.value = [];
  } finally {
    loading.value = false;
  }
};

// 加载父级任务选项
const loadParentTaskOptions = () => {
  const options = [];

  // 递归函数处理树形数据
  const processTasks = (tasks, level = 0) => {
    tasks.forEach(task => {
      options.push({
        value: task.id,
        label: '　'.repeat(level) + task.typeName,
        disabled: task.status === '0' // 停用的任务不能作为父级
      });

      if (task.children && task.children.length > 0) {
        processTasks(task.children, level + 1);
      }
    });
  };

  processTasks(taskTreeData.value);
  parentTaskOptions.value = options;
};

// 工具函数
const formatTaskTime = (timeStr) => {
  if (!timeStr) return '-';
  return timeStr;
};

const getTaskStatusType = (status) => {
  const statusMap = {
    '1': 'success',   // 正常
    '0': 'danger'     // 停用
  };
  return statusMap[status] || 'info';
};

const getTaskStatusText = (status) => {
  const statusMap = {
    '1': '正常',
    '0': '停用'
  };
  return statusMap[status] || '未知';
};

// 业务操作函数
const searchTasks = async () => {
  await loadTaskList()
}

const resetFilter = async () => {
  filterTaskName.value = ''
  filterStatus.value = ''
  await loadTaskList()
  ElMessage.info('已重置筛选条件')
}

const addNewTask = async () => {
  isEdit.value = false
  isChild.value = false
  resetForm()
  showAddDialog.value = true
}

const addChildTask = async (parentTask) => {
  isEdit.value = false
  isChild.value = true
  resetForm()
  taskForm.value.pid = parentTask.id
  showAddDialog.value = true
}

const editTask = async (row) => {
  isEdit.value = true
  isChild.value = false
  taskForm.value = {
    id: row.id,
    typeName: row.typeName,
    pid: row.pid,
    status: row.status.toString()
  }
  showAddDialog.value = true
}

const saveTask = async () => {
  try {
    // 检查表单引用是否存在
    if (!taskFormRef.value) {
      ElMessage.error('表单引用不存在，请重试');
      return;
    }

    // 清除之前的验证状态
    taskFormRef.value.clearValidate();

    // 验证必填字段
    const validationPromises = [
      taskFormRef.value.validateField('typeName'),
      taskFormRef.value.validateField('status')
    ];

    try {
      await Promise.all(validationPromises);
    } catch (error) {
      console.log('表单验证失败:', error);
      // 验证失败，不继续执行
      return;
    }

    saveLoading.value = true

    // 构建任务类型数据
    const taskData = {
      typeName: taskForm.value.typeName || '',
      pid: taskForm.value.pid || 0,
      status: taskForm.value.status || '1',
    }

    console.log('保存任务类型参数:', taskData);
    console.log('表单原始数据:', taskForm.value);
    console.log('是否为编辑模式:', isEdit.value);

    let result;
    if (isEdit.value) {
      // 更新任务类型
      console.log('调用更新任务类型API，id:', taskForm.value.id);
      result = await taskTypeAPI.updateTaskType(taskForm.value.id, taskData);
      console.log('更新任务类型API响应:', result);
    } else {
      // 添加新任务类型
      console.log('调用添加任务类型API');
      result = await taskTypeAPI.addTaskType(taskData);
      console.log('添加任务类型API响应:', result);
    }

    if (result && result.code === 0) {
      ElMessage.success(isEdit.value ? '任务类型更新成功' : '任务类型添加成功');
      showAddDialog.value = false;
      // 延迟重置表单，避免组件引用错误
      nextTick(() => {
        resetForm();
      });
      // 刷新任务类型列表
      await loadTaskList();
    } else {
      throw new Error(result?.msg || (isEdit.value ? '更新任务类型失败' : '添加任务类型失败'));
    }
  } catch (error) {
    console.error('保存任务类型失败:', error);
    ElMessage.error(`保存任务类型失败: ${error.message}`);
  } finally {
    saveLoading.value = false;
  }
}

const cancelEdit = () => {
  showAddDialog.value = false
  // 延迟重置表单，避免组件引用错误
  nextTick(() => {
    resetForm()
  })
}

const resetForm = () => {
  taskForm.value = {
    id: '',
    typeName: '',
    pid: 0,
    status: '1',
  }
  // 安全地重置表单字段
  nextTick(() => {
    if (taskFormRef.value && typeof taskFormRef.value.resetFields === 'function') {
      taskFormRef.value.resetFields()
    }
  })
}

const deleteTask = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除任务类型"${row.typeName}"吗？${row.children && row.children.length > 0 ? '\n\n注意：该任务类型有子级，删除后将一并删除！' : ''}`,
        '确认删除',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const result = await taskTypeAPI.deleteTaskType(row.id);

    if (result && result.code === 0) {
      ElMessage.success('删除成功');
      // 刷新任务类型列表
      await loadTaskList();
    } else {
      throw new Error(result?.msg || '删除任务类型失败');
    }
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除');
    } else {
      console.error('删除任务类型失败:', error);
      ElMessage.error(`删除任务类型失败: ${error.message}`);
    }
  }
}

onMounted(async () => {
  console.log('TaskManagement onMounted 被调用');
  await loadTaskList();
});
</script>

<style scoped>
.task-management {
  padding: 20px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.filter-bar {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.filter-controls {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.filter-controls .el-input,
.filter-controls .el-select,
.filter-controls .el-button {
  flex-shrink: 0;
}

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.table-controls {
  display: flex;
  gap: 10px;
}

.table-container {
  flex: 1;
  overflow: hidden;
  padding: 0 20px;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-top: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

.time-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.action-buttons {
  display: flex;
  gap: 5px;
  justify-content: center;
}
</style>
